package com.schoolhelper.notification.service.impl;

import com.schoolhelper.notification.domain.Notification;
import com.schoolhelper.notification.mapper.NotificationMapper;
import com.schoolhelper.notification.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 通知服务实现类
 */
@Service
public class NotificationServiceImpl implements NotificationService {
    
    private static final Logger logger = LoggerFactory.getLogger(NotificationServiceImpl.class);
    
    @Autowired
    private NotificationMapper notificationMapper;
    
    @Override
    public boolean createNotification(Notification notification) {
        try {
            System.out.println("=== 开始创建通知 ===");
            System.out.println("userId: " + notification.getUserId());
            System.out.println("type: " + notification.getType());
            System.out.println("title: " + notification.getTitle());
            System.out.println("content: " + notification.getContent());
            System.out.println("relatedId: " + notification.getRelatedId());
            System.out.println("relatedUserId: " + notification.getRelatedUserId());
            System.out.println("isRead: " + notification.getIsRead());
            
            if (notification.getCreateTime() == null) {
                notification.setCreateTime(LocalDateTime.now());
            }
            if (notification.getUpdateTime() == null) {
                notification.setUpdateTime(LocalDateTime.now());
            }
            
            System.out.println("准备插入数据库...");
            int result = notificationMapper.insertNotification(notification);
            System.out.println("数据库插入结果: " + result);
            System.out.println("通知ID: " + notification.getId());
            
            logger.info("创建通知成功: userId={}, type={}, title={}", 
                       notification.getUserId(), notification.getType(), notification.getTitle());
            return result > 0;
        } catch (Exception e) {
            System.err.println("创建通知异常: " + e.getMessage());
            e.printStackTrace();
            logger.error("创建通知失败: userId={}, type={}", 
                        notification.getUserId(), notification.getType(), e);
            return false;
        }
    }
    
    @Override
    public boolean createTaskNotification(Long userId, String type, String title, String content, Long taskId, Long relatedUserId) {
        try {
            Notification notification = new Notification(userId, type, title, content, taskId, relatedUserId);
            return createNotification(notification);
        } catch (Exception e) {
            logger.error("创建任务通知失败: userId={}, type={}, taskId={}", userId, type, taskId, e);
            return false;
        }
    }
    
    @Override
    public boolean createFriendRequestNotification(Long userId, String title, String content, Long requestId, Long relatedUserId) {
        try {
            Notification notification = new Notification(userId, "FRIEND_REQUEST", title, content, requestId, relatedUserId);
            return createNotification(notification);
        } catch (Exception e) {
            logger.error("创建好友请求通知失败: userId={}, requestId={}", userId, requestId, e);
            return false;
        }
    }
    
    @Override
    public List<Notification> getUserNotifications(Long userId, int page, int size) {
        try {
            int offset = (page - 1) * size;
            return notificationMapper.findByUserId(userId, size, offset);
        } catch (Exception e) {
            logger.error("获取用户通知列表失败: userId={}", userId, e);
            return null;
        }
    }
    
    @Override
    public int getUnreadCount(Long userId) {
        try {
            return notificationMapper.getUnreadCount(userId);
        } catch (Exception e) {
            logger.error("获取未读通知数量失败: userId={}", userId, e);
            return 0;
        }
    }
    
    @Override
    public List<Notification> getUnreadNotifications(Long userId) {
        try {
            return notificationMapper.findUnreadByUserId(userId);
        } catch (Exception e) {
            logger.error("获取未读通知列表失败: userId={}", userId, e);
            return null;
        }
    }
    
    @Override
    public boolean markAsRead(Long notificationId) {
        try {
            int result = notificationMapper.markAsRead(notificationId);
            return result > 0;
        } catch (Exception e) {
            logger.error("标记通知已读失败: notificationId={}", notificationId, e);
            return false;
        }
    }
    
    @Override
    public boolean markAsRead(Long notificationId, Long userId) {
        try {
            // 带用户权限验证的标记已读
            int result = notificationMapper.markAsReadWithUserCheck(notificationId, userId);
            logger.info("标记通知已读: notificationId={}, userId={}, result={}", notificationId, userId, result);
            return result > 0;
        } catch (Exception e) {
            logger.error("标记通知已读失败: notificationId={}, userId={}", notificationId, userId, e);
            return false;
        }
    }
    
    @Override
    public boolean markAllAsRead(Long userId) {
        try {
            int result = notificationMapper.markAllAsRead(userId);
            logger.info("标记所有通知已读: userId={}, count={}", userId, result);
            return true;
        } catch (Exception e) {
            logger.error("标记所有通知已读失败: userId={}", userId, e);
            return false;
        }
    }
    
    @Override
    public boolean deleteNotification(Long notificationId) {
        try {
            int result = notificationMapper.deleteNotification(notificationId);
            return result > 0;
        } catch (Exception e) {
            logger.error("删除通知失败: notificationId={}", notificationId, e);
            return false;
        }
    }
}